//
// Created by yangentao on 2021/1/31.
//

import Foundation


@propertyWrapper
public struct UserDefault<T> {
    var key: String
    var defaultValue: T

    public init(_ key: String, _ defaultValue: T) {
        self.key = key
        self.defaultValue = defaultValue
    }

    public var wrappedValue: T {
        get {
            let old = UserDefaults.standard.object(forKey: key)
            if (old == nil) {
                UserDefaults.standard.set(defaultValue, forKey: key)
                return defaultValue
            }
            return old as! T
        }
        set {
            UserDefaults.standard.set(newValue, forKey: key)
        }
    }

}

@propertyWrapper
public struct UserModel<T: Codable> {
    var key: String
    var model: T? = nil

    public init(_ key: String) {
        self.key = key
    }

    public var wrappedValue: T? {
        mutating get {
            if model != nil {
                return model
            }
            if let s = UserDefaults.standard.string(forKey: key), s.notEmpty {
                let m: T? = YsonObject(s)?.toModel()
                self.model = m
                return m
            }
            return nil
        }
        set {
            model = newValue
            let s: String? = newValue?.toYson().yson
            UserDefaults.standard.set(s, forKey: key)
        }
    }
}


public func userListPut<T: Codable>(key: String, items: [T]) {
    UserDefaults.standard.set(items.toYson().yson, forKey: key)
}

public func userListGet<T: Codable>(key: String) -> [T] {
    if let s = UserDefaults.standard.string(forKey: key), s.notEmpty {
        return YsonArray(s)?.toModel() ?? []
    }
    return []
}